<template>

  <el-card shadow="never" class="border-0">
    <!-- 搜索 -->
    <SearchForm :model="searchForm" @search="getList" @reset="resetSearchForm">
      <SearchItem label="">

        <div class="mt-4" style="width: 100%;">
          <el-input v-model="searchForm.name" placeholder="用户组名" class="input-with-select">
            <template #prepend>
              <el-button :icon="Search" />
            </template>
          </el-input>
        </div>


      </SearchItem>
    </SearchForm>


    <!-- 新增|刷新 -->
    <ListHeader layout="create,refresh" @create="handleCreate" @refresh="getList" />

    <el-table :data="tableData" stripe style="width: 100%; text-align: center" v-loading="loading" border>
      <el-table-column type="index" label="序号" style="text-align: center" width="100" align="center " />
      <el-table-column prop="name" label="组名" width="300" style="text-align: center" align="center " />

      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button @click="handleEdit(scope.row)" text type="primary" class="p-1">
            <el-icon class="el-icon--left" :size="16">
              <Edit />
            </el-icon>修改
          </el-button>

          <el-button @click="configPermissions(scope.row)" text type="primary" class="p-1">
            <el-icon class="el-icon--left" :size="16">
              <Tools />
            </el-icon>配置权限
          </el-button>

          <el-popconfirm title="是否要删除？" confirmButtonText="确认" cancelButtonText="取消"
            @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button text type="danger" class="p-1">
                <el-icon class="el-icon--left" :size="16">
                  <Delete />
                </el-icon>删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="flex items-center justify-center mt-5">
      <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
        :page-size="pageSize" @current-change="getList" />
    </div>


    <!-- 新增/修改 -->
    <FormDrawer destroyOnClose ref="formDrawerRef" size="30%" :title="drawerTitle" @submit="handleSubmit">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="150px" :inline="false">
        <el-form-item label="组名" prop="name">
          <el-input v-model="form.name" placeholder="组名"></el-input>
        </el-form-item>
      </el-form>
    </FormDrawer>


    <!-- 配置权限 -->
    <el-drawer destroyOnClose v-model="isConfigPermissions" :title="permissionsTitle" size="30%" direction="rtl">
      <template #default>
        <el-input v-model="filterText" placeholder="Filter keyword" />

        <el-tree ref="treeRef" class="filter-tree" :data="menuData" :check-strictly="true"
          :default-checked-keys="has_rules" node-key="id" show-checkbox :props="defaultProps" default-expand-all
          :filter-node-method="filterNode">

          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
            </span>
          </template>
        </el-tree>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">返回</el-button>
          <el-button type="primary" @click="confirmClick">提交</el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>

</template>
<script setup>
// vue 内部方法
import { ref, onMounted, watch } from 'vue'
import {useStore} from 'vuex'

// 页面组件
import ListHeader from "~/components/ListHeader.vue"
import FormDrawer from "~/components/FormDrawer.vue"
import SearchForm from "~/components/SearchForm.vue"
import SearchItem from "~/components/SearchItem.vue"
import UploadFile from "~/components/UploadFile.vue"
import { Search } from '@element-plus/icons-vue'

// 公共方法
import { useInitTable, useInitForm } from "~/composables/useCommon"
import { toast } from "~/composables/util";

// api
import {
  getGroups,
  postGroups,
  putGroups,
  deleteGroups,
} from "~/api/user/group"


import { getMenusList } from "~/api/system/menu"

const store = useStore()

// 初始化表格
const {
  searchForm,
  resetSearchForm,
  tableData,
  loading,
  currentPage,
  total,
  pageSize,
  getList,
  handleDelete,
} = useInitTable({
  searchForm: { search: "", name: "" },
  requestListAPI: getGroups,
  delete: deleteGroups,
  onGetListSuccess: (res) => {
    tableData.value = res.data
  },
})

// 初始化表单
const {
  formDrawerRef,
  formRef,
  form,
  rules,
  editId,
  drawerTitle,
  handleSubmit,
  resetForm,
  handleCreate,
  handleEdit,
} = useInitForm({
  getList,
  create: postGroups,
  update: putGroups,
  form: {
    name: "",
  },
  // onGetDataSuccess: (res) => {
  //   // 将接口返回的公司列表数据命名为companyAllList
  //   companyAllList.value = res.data.name;
  // },
  rules: {
    name: [
      {
        required: true,
        message: "名称不能为空",
        trigger: "blur",
      },
    ],
  }

});




// 取消配置权限
const cancelClick = () => {
  isConfigPermissions.value = false
}

// 确认配置权限
const confirmClick = () => {
  let checkedKeys = treeRef.value.getCheckedKeys();
  putGroups(form.id,
    {
      rules: checkedKeys.join(","),
      name: form.name
    })
    .then(res => {
      toast("修改权限成功");
      getList()
      isConfigPermissions.value = false
    }).finally(r => {
      // 获取用户信息
      // 直接请求用户数据
      store.dispatch("getUserInfo").then().finally(() => {
      })
    })
}

// 菜单列表
const menuData = ref([])

// 菜单数据
const filterText = ref('')
const treeRef = ref('')
const has_rules = ref([])
const defaultProps = { label: 'name', childern: "childern" }

watch(filterText, (val) => {
  treeRef.value = !treeRef.value.filter(val)
})

const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}


// 请求权限数据
onMounted(() => {
  getMenusList()
    .then(res => {
      menuData.value = res.data
    })
})


// 配置权限
const isConfigPermissions = ref(false)
const permissionsTitle = ref('')
const configPermissions = (row) => {
  form.name = row.name
  form.id = row.id
  isConfigPermissions.value = true
  permissionsTitle.value = "配置权限 -- " + row.name
  if (row.rules.length > 0) {
    has_rules.value = row.rules.split(",")
  } else {
    has_rules.value = []
  }
}
</script>

<style scoped></style>
